﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Dapper;
using Microsoft.IdentityModel.Tokens;
using Entity;
using IRealize;
using Realize;
using System.Data;
using System.Threading.Tasks;

namespace WebApplication9.Controllers.HRFA
{
    public class RLCXController : Controller
    {
        private readonly IConfiguration configuration;

        public RLCXController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Index2()
        {
            return View();
        }


        // 获取级联数据（I级→II级→III级）
        [HttpGet("FirstLevelCX")]
        public async Task<IActionResult> FirstLevelCX()
        {

            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 1. 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT first_kind_id AS id, first_kind_name AS name 
              FROM config_file_first_kind 
              WHERE first_kind_id IS NOT NULL AND first_kind_name IS NOT NULL");


                // 2. 查询II级机构
                var secondKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT first_kind_id AS parentId, 
                     second_kind_id AS id, 
                     second_kind_name AS name 
              FROM config_file_second_kind 
              WHERE second_kind_id IS NOT NULL AND second_kind_name IS NOT NULL");


                // 3. 查询III级机构
                var thirdKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT second_kind_id AS parentId, 
                     third_kind_id AS id, 
                     third_kind_name AS name 
              FROM config_file_third_kind 
              WHERE third_kind_id IS NOT NULL AND third_kind_name IS NOT NULL");

                // 4. 构建级联数据（使用实体类）
                var result = new List<CascaderNode>();

                foreach (var first in firstKinds)
                {
                    var firstId = first.id;
                    var seconds = secondKinds.Where(s => s.parentId == firstId).ToList();

                    var secondList = new List<CascaderNode>(); // 明确为CascaderNode列表

                    foreach (var second in seconds)
                    {
                        var secondId = second.id;
                        // 构建III级节点（实体类）
                        var thirds = thirdKinds
                            .Where(t => t.parentId == secondId)
                            .Select(t => new CascaderNode
                            {  // 使用实体类
                                id = t.id,
                                name = t.name,
                                children = new List<CascaderNode>() // 子节点也是实体类列表
                            })
                            .ToList();

                        // 构建II级节点（实体类），此时thirds和空列表类型一致
                        secondList.Add(new CascaderNode
                        {
                            id = second.id,
                            name = second.name,
                            children = thirds.Any() ? thirds : new List<CascaderNode>() // 都是List<CascaderNode>
                        });
                    }

                    // 构建I级节点（实体类）
                    result.Add(new CascaderNode
                    {
                        id = first.id,
                        name = first.name,
                        children = secondList.Any() ? secondList : new List<CascaderNode>() // 类型一致
                    });
                }

                return Ok(result);
            }

        }


        [HttpGet("JobCategoryCX")]
        public async Task<IActionResult> JobCategoryCX()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 1. 查询所有职位分类（第1级）
                var categories = await connection.QueryAsync<dynamic>(
                    @"SELECT major_kind_id AS id, major_kind_name AS name 
              FROM config_major_kind");

                // 2. 查询所有职位（第2级）
                var jobs = await connection.QueryAsync<dynamic>(
                    @"SELECT major_kind_id AS parentId, major_id AS id, major_name AS name 
              FROM config_major");

                // 3. 构建级联数据（使用实体类）
                var result = new List<CascaderNode>();

                foreach (var category in categories)
                {
                    var categoryId = category.id;
                    var categoryJobs = jobs.Where(j => j.parentId == categoryId).ToList();

                    // 构建职位列表（第2级节点）
                    var jobList = categoryJobs.Select(job => new CascaderNode
                    {
                        id = job.id,
                        name = job.name,
                        children = new List<CascaderNode>() // 确保children存在
                    }).ToList();

                    // 构建职位分类节点（第1级节点）
                    result.Add(new CascaderNode
                    {
                        id = category.id,
                        name = category.name,
                        children = jobList.Any() ? jobList : new List<CascaderNode>()
                    });
                }

                return Ok(result);
            }
        }



        public async Task<IActionResult> Search([FromBody] Human_File request)
        {

            IRLXLK rLXLK = new RLXLK();



            // 调用服务层执行查询
            var result = await rLXLK.SearchHumanFiles(
               configuration["SqlServer"],
                request.first_kind_name,
                request.second_kind_name,
                request.third_kind_name,
                request.human_major_kind_name,
                request.hunma_major_name,
                request.regist_time,
                request.check_time,
                request.PageNumber,  
                request.PageSize

            );


            // 返回分页结果
            return Ok(new
            {
                TotalCount = result.TotalCount,
                Items = result.Items,
                PageNumber = result.PageNumber,
                PageSize = result.PageSize
            });


        }



        public IActionResult CXXS()
        {
            return View();
        }




        public async Task<IActionResult> RLCK(int id)
        {
            return View();

        }


        public async Task<IActionResult> CXZS(int id)
        {
            IRLXLK rLXLK = new RLXLK();
            Human_File fileDig = await rLXLK.SelectHFIDAsync(id, configuration["SqlServer"]);


            // 映射数据为前端需要的格式，包含原机构和原职位ID
            var result = new
            {
                success = true,
                data = new
                {


                    huf_id = fileDig.huf_id,
                    human_id = fileDig.human_id,
                    human_name = fileDig.human_name,
                    human_id_card = fileDig.human_id_card,
                    first_kind_name = fileDig.first_kind_name,
                    second_kind_name = fileDig.second_kind_name,
                    third_kind_name = fileDig.third_kind_name,
                    human_major_kind_name = fileDig.human_major_kind_name,
                    hunma_major_name = fileDig.hunma_major_name,
                    human_pro_designation = fileDig.human_pro_designation,
                    human_sex = fileDig.human_sex,
                    human_email = fileDig.human_email,
                    human_mobilephone = fileDig.human_mobilephone,
                    human_qq = fileDig.human_qq,
                    human_telephone = fileDig.human_telephone,
                    human_address = fileDig.human_address,
                    human_postcode = fileDig.human_postcode,
                    human_nationality = fileDig.human_nationality,
                    human_birthplace = fileDig.human_birthplace,
                    human_birthday = fileDig.human_birthday,
                    human_race = fileDig.human_race,
                    human_religion = fileDig.human_religion,
                    human_party = fileDig.human_party,
                    human_society_security_id = fileDig.human_society_security_id,
                    human_age = fileDig.human_age,
                    human_educated_degree = fileDig.human_educated_degree,
                    human_educated_years = fileDig.human_educated_years,
                    human_educated_major = fileDig.human_educated_major,
                    salary_standard_name = fileDig.salary_standard_name,
                    human_bank = fileDig.human_bank,
                    human_account = fileDig.human_account,
                    checker = fileDig.checker,
                    check_time = fileDig.check_time,
                    human_speciality = fileDig.human_speciality,
                    human_hobby = fileDig.human_hobby,
                    attachment_name = fileDig.attachment_name,
                    human_histroy_records = fileDig.human_histroy_records,
                    human_family_membership = fileDig.human_family_membership,
                    remark = fileDig.remark,
                    human_picture = fileDig.human_picture,


                }

            };

            return Ok(result);

        }



        public IActionResult Index3()
        {
            return View();
        }



        public async Task<IActionResult> Index4(int pageSize, int currentPage)
        {

            string sqlserver = configuration["SqlServer"];
            using (SqlConnection conn = new SqlConnection(sqlserver))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@keyName", "huf_id");
                param.Add("@tableName", "human_file");
                param.Add("@currentPage", currentPage);
                param.Add("@totalRows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYedd] @pageSize, @keyName, @tableName, @currentPage, @totalRows out";
                List<Human_File> list = conn.Query<Human_File>(sql, param).ToList();

                FenYe<Human_File> fenYecs = new FenYe<Human_File>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("totalRows");
                //return fenYecs;
                return Json(fenYecs);

            }


        }


        public async Task<IActionResult> RLCK1(int id)
        {
            return View();
        }


    }
}
